package A011thread;

/**
 * 注意点：使用synchronized 锁class字节码，多线程只会有一个线程进行操作
 */
public class A006_Thread_方法一_4个线程加一减一 {

    public static class Data {
        private int number = 0;

        /**
         * 增量方法，number + 1
         */
        public synchronized void increment() throws InterruptedException {
            while (number != 0){
                // 等待
                this.wait();
            }
            // 开始具体的业务逻辑
            number++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            // 加完后，通知其他线程 +1 操作完毕了
            this.notifyAll();
        }

        /**
         * 减量操作，number - 1
         */
        public synchronized void decrement() throws InterruptedException {
            while (number == 0){
                // 等待
                this.wait();
            }
            // 开始具体的业务逻辑
            number--;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            // 减完后，通知其他线程 -1 操作完毕了
            this.notifyAll();
        }
    }

    public static void main(String[]args){
        Data data = new Data();
        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(()->{
            for (int i = 0;i<10;i++){
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }


}
